package com.sanben.common.util;

import cn.hutool.json.JSONObject;
import com.sanben.common.constant.Constant;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author ch
 * @Description 秒滴短信工具类
 * @date 2019/9/2 15:19
 */
public class SsmUtil {

    /**
     * 秒嘀短信发送
     *
     * @param mobile     手机号
     * @param smsContent 模板
     * @return
     */
    public static String sendSms(String mobile, String smsContent) {
        //获取当前时间戳
        String timestamp = System.currentTimeMillis()+"";
        //验证信息用MD5加密
        StringBuffer source = new StringBuffer();
        source.append(Constant.ACCOUNT_SID).
                append(Constant.AUTH_TOKEN).
                append(timestamp);
        String sig = MD5Util.encrypt(source.toString());
        OutputStreamWriter out;
        BufferedReader br;
        StringBuilder result = new StringBuilder();
        try {
            URL url = new URL(Constant.QUERY_PATH);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            // 设置是否允许数据写入
            connection.setDoInput(true);
            // 设置是否允许参数数据输出
            connection.setDoOutput(true);
            // 设置链接响应时间
            connection.setConnectTimeout(5000);
            // 设置参数读取时间
            connection.setReadTimeout(10000);
            connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
            // 提交请求
            out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
            StringBuffer args = new StringBuffer();
            args.append("accountSid=").append(Constant.ACCOUNT_SID).
                    append("&smsContent=").append(smsContent).
                    append("&to=").append(mobile).
                    append("&timestamp=").append(timestamp).
                    append("&sig=").append(sig).
                    append("&respDataType=").append("JSON");
            out.write(args.toString());
            out.flush();
            // 读取返回参数
            br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String temp;
            while ((temp = br.readLine()) != null) {
                result.append(temp);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        JSONObject json =new JSONObject(result.toString());
        String respCode = json.getStr("respCode");
        String defaultRespCode = "0000";
        if (Constant.SMS_SUCCESS.equals(respCode)) {
            return defaultRespCode;
        }
        return null;
    }
}


